import { hasValue } from '../../utils/util'
import { fetchPlayerList, checkLogin } from '../../api/index';

const defaultAvatarUrl = 'https://fks.yiquhz.com/gulu/3ec4c.jpg'
Component({
  data: {
    showBtn: true,
    motto: '游戏宝 1.0',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    openId: '',
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },
  methods: {
    onLoad() {
      //如果本地储存的openid有值
      if (hasValue(wx.getStorageSync("openId"))) {
        this.getPlayerList(wx.getStorageSync("openId"))
      } else {
        const openid = checkLogin();
        openid.then(item => {
          if (item) {
            this.setData({
              openId: item
            })
          }
        })
      }
    },
    getPlayerList: async function (openId: string) {
      try {
        const playerList = await fetchPlayerList(openId, false);
        if (!playerList.length) {
          wx.redirectTo({ url: "/pages/error/error" });
          return
        }
        //获取用户昵称
        this.setData({
          userInfo: {
            avatarUrl: defaultAvatarUrl,
            nickName: playerList[0].wechatName
          },
          hasUserInfo: true,
          openId: openId
        })
        wx.setStorageSync('openId', openId)
        wx.setStorageSync('wechatName', playerList[0].wechatName)
      } catch (err) {
        wx.redirectTo({ url: "/pages/empty/empty" });
      }
    },
    onInputChange(e: any) {
      const nickName = e.detail.value
      this.setData({
        "userInfo.nickName": nickName,
        hasUserInfo: nickName,
      })
    },
    getUserProfile() {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    },
    goBind() {
      wx.setStorageSync('openId', this.data.openId)
      wx.setStorageSync('wechatName', this.data.userInfo.nickName)
      wx.reLaunch({
        url: '/pages/index/index'
      })
    }
  },
})
